import { CommonModel } from "../api/api-common/commonModel.js"
const commonModel = new CommonModel();
const App = getApp();

// 获取授权手机号，绑定用户
export function bindUser(e) {
	return new Promise((resolve, reject) => {
		// 获取手机号
		commonModel.getPhoneNumberApi({ code: e.detail.code }).then(response => {
			if (response.errcode == 0) {
				// wx.login()获取code
				wx.login({
					success: (res) => {
						// 通过code进行用户绑定
						commonModel.bindUserApi({ code: res.code, mobile: response.phone_info.phoneNumber }).then(resp => {
							// 再获取一遍code
							wx.login({
								success: (result) => {
									// 登录获取token
									commonModel.loginApi({ code: result.code }).then(token => {
										if (token == undefined) {
											// 登录失败
											// 存储token
											App.globalData.token = "";
											App.globalData.isBind = false;
											// 登录失败
											resolve({ bind_code: 401 })
										}
										else {
											// 登录成功
											// 存储token
											App.globalData.token = token;
											App.globalData.isBind = true;
											resolve({ bind_code: 200 })
										}
									})
								},
							})
						})
					}
				})
			}
		})
	})
}

// 判断用户是否授权过
export function isBindUser() {
	return new Promise((resolve, reject) => {
		wx.login({
			success: (res) => {
				commonModel.loginApi({ code: res.code }).then(token => {
					if (token == undefined) {
						// 没有授权过，去登录
						App.globalData.isBind = false; // 没有授权绑定过，去登录
						App.globalData.username = "";
						App.globalData.token = "";
						resolve(null)
					}
					else {
						// 授权过，存储token
						App.globalData.token = token;
						// 获取用户信息
						commonModel.getInfosApi().then(result => {
							App.globalData.username = result.name == null || result.name == "" ? "微信授权用户" : result.name;
							App.globalData.openid = result.openid;
							resolve(result)
						})
					}
				})
			}
		})
	})
}